<template>
  <div class="bg-[#f6f7fb] dark:bg-transparent m-[-16px] p-[16px] mb-[-14px] pb-[22px]" v-loading="isloadinga">
    <div class="flex overflow-hidden" :class="isshow ? '' : 'h-[32px]'">
      <div class="flex flex-wrap gap-[10px]" ref="listheight">
        <!-- <el-descriptions ref="ruleFormRef" :column="1" direction="horizontal">
          <el-descriptions-item width="50%" label="最近上报时间">
            {{ isNullOrEmpty(currentdatas?.CreatedAt) }}
          </el-descriptions-item>
        </el-descriptions> -->
        <div v-auth="'business.control.command'" v-for="(item, index) in deviceinfo?.commandInfo" :key="index"
          class="flex gap-[10px] listha w-[calc(100% - 60px)]">
          <div>
            <el-button type="primary" plain size="small" @click="commanddevice(item)">
              {{ isNullOrEmpty(item.commandName) }}</el-button>
          </div>
        </div>
      </div>
      <div class="w-[60px]" v-if="showdow">
        <div
          class="flex items-center justify-center w-[30px] h-[30px] dark:bg-[#16192c] bg-[#999] rounded-[50%] cursor-pointer"
          @click="isshow = !isshow">
          <el-icon v-if="isshow" class="text-[20px]">
            <ArrowUp />
          </el-icon>
          <el-icon v-else class="text-[20px]">
            <ArrowDown />
          </el-icon>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <div v-auth="'business.device-data.current'" class="pt-[16px] h-[762px] flex gap-[16px]">
      <!-- 左侧 -->
      <div class="flex-[308] relative p-[16px] dark:bg-[rgba(46,51,73,0.6)] bg-[#fff] flex flex-col">
        <div class="flex items-center">
          <div class="w-[4px] h-[15px] bg-[#2478CE] rounded-[2px] mr-[11px]"></div>
          <div class="text-[16px] font-medium leading-[1] mr-[11px] dark:text-[#FFFFFF]">
            运行状态
          </div>
          <div class="text-[14px] text-[#9095A8;] font-medium leading-[1]">
            {{ isNullOrEmpty(currentdatas?.CreatedAt) }}
          </div>
        </div>
        <div class="flex-1 h-0 relative">
          <el-scrollbar>
            <div class="grid grid-cols-2 gap-[16px] mt-[16px]">
              <div v-for="(item, index) in deviceinfo?.structInfo" :key="index"
                class="rounded-[4px] bg-[#F6F7FB] dark:bg-[#2E3349]">
                <div class="text-[18px] font-bold font-[D-DIN] text-center pt-[22px] leading-[1] dark:text-[#FFFFFF]">
                  {{
                    isNullOrEmpty(`${currentdatas[item?.fieldAlias] ?? "--"} `)
                  }}{{ item?.unit }}
                  <!-- {{ index }} -->
                </div>
                <div class="text-[14px] text-center leading-[1] pt-[12px] pb-[21px] dark:text-[#D6D6D6]">
                  {{ isNullOrEmpty(isNullOrEmpty(item?.fieldName)) }}
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="flex-[832] relative p-[16px] dark:bg-[rgba(46,51,73,0.6)] bg-[#fff] rounded-[4px]">
        <div class="flex items-center">
          <div class="w-[4px] h-[15px] bg-[#2478CE] rounded-[2px] mr-[11px]"></div>
          <div class="text-[16px] font-medium leading-[1] mr-[11px] dark:text-[#FFFFFF]">
            数据分析
          </div>
        </div>

        <div class="mb-[16px]">
          <div class="flex justify-between bg-[#F6F7FB] dark:bg-[#2E3349] mt-[16px]">
            <div v-for="(, key) in topText" :key="key" class="text-center flex-1 pt-[27px] pb-[19px]">
              <div class="">
                <div class="leading-[1] text-[18px] font-bold font-[D-DIN]" style="
                    -webkit-background-clip: text;
                    -webkit-text-fill-color: transparent;
                  " :class="topText[key].text == '待确认'
                    ? 'bg-[linear-gradient(0deg,#E89029_0%,#FFFFFF_98.92578125%)]'
                    : topText[key].text == '处理中'
                      ? 'bg-[linear-gradient(0deg,#07C7E0_0%,#FFFFFF_98.92578125%)]'
                      : 'bg-[linear-gradient(0deg,#5784E9_0%,#FFFFFF_98.92578125%)]'
                    ">
                  <div v-if="topText[key].value <= 999">
                    {{ topText[key].value }}
                  </div>
                  <div v-else>999+</div>
                </div>
                <div class="leading-[1] pt-[12px] text-[14px] font-normal">
                  {{ topText[key].text }}
                </div>
              </div>
            </div>
          </div>

          <!-- echart -->
          <div class="line-card mt-[16px] dark:bg-[rgba(46,51,73,0.6)] bg-[#fff] rounded-[4px]">
            <div class="text-[14px] leading-[1] pt-[24px] pl-[24px] pb-[21px] dark:text-[#D6D6D6]">
              近15日告警态势
            </div>
            <lines :data="linesData" :height="220" />
          </div>
          <div class="bar-card mt-[16px] dark:bg-[rgba(46,51,73,0.6)] bg-[#fff] rounded-[4px]">
            <div class="text-[14px] leading-[1] pt-[24px] pl-[24px] pb-[21px] dark:text-[#D6D6D6]">
              告警事件统计
            </div>
            <bar :data="barData" :height="220" />
          </div>
        </div>
      </div>
    </div>
    <!-- <div v-auth="'business.device-data.current'" class="grid grid-cols-5 gap-[16px]">
      <div class="h-[100px] flex justify-center flex-col items-center bg-[#F6F7FB] dark:bg-[#2E3349]"
        v-for="(item, index) in deviceinfo?.structInfo" :key="index">
        <div>
          <div class="text-[22px] leading-[22px] font-bold font-[D-DIN] text-center dark:text-[#FFFFFF]">
            {{ isNullOrEmpty(`${currentdatas[item?.fieldAlias] ?? '--'} `) }}
          </div>
          <div class="pt-[12px] text-[14px] leading-[14px] text-center dark:text-[#D6D6D6]">
            {{ isNullOrEmpty(isNullOrEmpty(item?.fieldName)) }}
          </div>
        </div>
      </div>
    </div> -->
  </div>
</template>
<script setup lang="ts">
import { ElLoading } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import dataselect from "./dataselect.vue";
import { addDialog, closeDialog } from "@/components/ReDialog";
import {
  getControlops,
  currentdata,
  getdevicealarm,
  commandconfig
} from "@/api/operate/device-management/index";
import { ArrowDown, ArrowUp } from "@element-plus/icons-vue";
import { isNullOrEmpty } from "@/utils/functions";
import bar from "./bar.vue";
import datainput from "./datainput.vue";
import lines from "./line.vue";
import { isEmpty, isFunction } from "@pureadmin/utils";
import { customPromiseDebounce } from '@/utils/functions'
const props = defineProps({
  deviceId: {
    type: String,
    default: ""
  },
  deviceinfo: {
    type: Object,
    default: () => ({})
  }
});
const isshow = ref(false);
const isloadinga = ref(false);
const selectidvalue1 = ref(null)
// const debounceGetControlops = customPromiseDebounce(getControlops, 500, true)
const topText = ref({
  today: {
    text: "今日告警",
    value: 0
  },
  week: {
    text: "本周告警",
    value: 0
  },
  month: {
    text: "本月告警",
    value: 0
  },
  year: {
    text: "本年告警",
    value: 0
  },
  wait: {
    text: "待确认",
    value: 0
  },
  dealing: {
    text: "处理中",
    value: 0
  }
});
const currentdatas: any = ref({});
const formRef = ref(null);
const selectidvalue = ref(null);
const timer = ref(null);
const listheight = ref(null);
const showdow = ref(false);
onMounted(() => {
  getdatsa()
  timer.value = setInterval(() => {
    getdatsa()
  }, 5000);
  nextTick(() => {
    const sumWidths = calculateSumWidths(listheight.value);
    if (sumWidths > 1100) {
      showdow.value = true;
    } else {
      showdow.value = false;
    }
  });
  devicealarm(); //获取曲线图数据
});
function getdatsa() {
  currentdata({ deviceId: props.deviceId }).then(res => {
    currentdatas.value = res.result.data;
  });
}
function calculateSumWidths(element) {
  let sum = 0;
  const children = element.childNodes;
  for (let i = 0; i < children.length; i++) {
    const child = children[i];
    if (child.offsetWidth) {
      sum += child.offsetWidth + 10;
    }
  }
  return sum;
}
watch(
  () => props.deviceinfo?.commandInfo,
  () => {
    setTimeout(() => {
      const sumWidths = calculateSumWidths(listheight.value);
      console.log(sumWidths, "宽度之和");
      if (sumWidths > 1100) {
        showdow.value = true;
      } else {
        showdow.value = false;
      }
    }, 500);
  }
);
onBeforeUnmount(() => {
  timer.value && clearInterval(timer.value);
});
const linesData = ref({
  endValue: 11,
  height: "200px",
  data: [],
  xAxis: []
}); // 折线图数据

/** 层叠柱状图 */
const barData = ref({
  endValue: 12,
  height: "200px",
  data: [],
  xAxis: []
});
const devicealarm = () => {
  //获取统计数据
  getdevicealarm({ deviceId: props.deviceId }).then(res => {
    for (const key in res.result) {
      if (topText.value[key]) {
        topText.value[key].value = res.result[key];
      }
    }

    if (!isEmpty(res.result?.alarmDays)) {
      //近15日
      linesData.value.xAxis = res.result.alarmDays.xAxis;
      linesData.value.data.push(
        ...res.result?.alarmDays.data.map((item, index) => {
          const colors = ["#07C7E0", "#5069DA", "#EEBC66"];
          return {
            name: item.name,
            value: item.value,
            color: colors[index]
          };
        })
      );
    }

    if (!isEmpty(res.result?.alarmMonth)) {
      //告警统计
      barData.value.xAxis = res.result.alarmMonth.xAxis;
      barData.value.data.push(
        ...res.result?.alarmMonth.data.map((item, index) => {
          const colors = ["#07C7E0", "#EEBC66", "#5069DA"];
          return {
            name: item.name,
            value: item.value,
            color: colors[index]
          };
        })
      );
    }
  });
};
const commanddevice = (item: any) => {
  selectidvalue.value = null;
  const loading = ref(false)
  if (item.paramType == 1) {
    addDialog({
      title: item.commandName,
      width: "428px",
      draggable: true,
      fullscreenIcon: true,
      props: {
        options: item.value3,
        modelValue: null,
        isLoading: true
      },
      hideFooter: false,
      closeOnClickModal: false,
      footerButtons: [
        {
          label: "取消",
          text: false,
          bg: true,
          btnClick: ({ dialog: { options, index } }) => {
            const done = () =>
              closeDialog(options, index, { command: "cancel" });
            if (options?.beforeCancel && isFunction(options?.beforeCancel)) {
              options.beforeCancel(done, { options, index });
            } else {
              done();
            }
          }
        },
        {
          label: "确定",
          type: "primary",
          text: false,
          bg: true,
          loading: loading,
          btnClick: ({ dialog: { options, index } }) => {
            const done = () =>
              closeDialog(options, index, { command: "sure" });
            if (options?.beforeSure && isFunction(options?.beforeSure)) {
              options.beforeSure(done, { options, index });
            } else {
              done();
            }
          }
        }
      ],
      contentRenderer: () =>
        h('div', `确定要执行${item.commandName}命令吗?`),
      beforeSure: (done) => {
        loading.value = true
        getControlops({
          deviceId: props.deviceId,
          commandId: item.commandId
        }).then((res: any) => {
          if (res.code == 200) {
            ElMessage({
              type: "success",
              message: res.msg
            });
            getdatsa()
            done()
          }
        }).finally(() => {
          loading.value = false
        });
      }
    });
  } else if (item.paramType == 2) {
    addDialog({
      title: item.commandName,
      width: "428px",
      draggable: true,
      fullscreenIcon: true,
      props: {
        options: item.value3,
        modelValue: null,
        isLoading: true
      },
      hideFooter: false,
      closeOnClickModal: false,
      footerButtons: [
        {
          label: "取消",
          text: false,
          bg: true,
          btnClick: ({ dialog: { options, index } }) => {
            const done = () =>
              closeDialog(options, index, { command: "cancel" });
            if (options?.beforeCancel && isFunction(options?.beforeCancel)) {
              options.beforeCancel(done, { options, index });
            } else {
              done();
            }
          }
        },
        {
          label: "确定",
          type: "primary",
          text: false,
          bg: true,
          loading: loading,
          btnClick: ({ dialog: { options, index } }) => {
            const done = () =>
              closeDialog(options, index, { command: "sure" });
            if (options?.beforeSure && isFunction(options?.beforeSure)) {
              options.beforeSure(done, { options, index });
            } else {
              done();
            }
          }
        }
      ],
      contentRenderer: () =>
        h(datainput, {
          ref: formRef,
          "onUpdate:modelValue": val => {
            selectidvalue1.value = val;
          }
        }),
      openAutoFocus({ options }) {
        options.props = {
          isLoading: true,
          formInline: {
            inputvalue: null
          },
          qujianzhi: item,
          activevalue: null
        };
        if (item.hasConfig == 1) {
          commandconfig({
            deviceSN: props.deviceinfo.deviceSN,
            commandAlias: item.commandAlias
          })
            .then(res => {
              options.props.formInline.inputvalue = res.result
              options.props.isLoading = false;
            })
            .catch(() => {
              options.props.isLoading = false;
              ElMessage({
                type: "error",
                message: "读取配置失败"
              });
            });
        } else {
          options.props.isLoading = false;
        }

      },
      beforeSure: (done, { options }) => {
        const formData = options.props.formInline;
        if (formData.inputvalue == null) {
          ElMessage({
            type: "warning",
            message: "请输入参数值"
          });
          return;
        }
        loading.value = true
        getControlops({
          deviceId: props.deviceId,
          commandId: item.commandId,
          commandArg: formData.inputvalue
        }).then((res: any) => {
          if (res.code == 200) {
            done();
            ElMessage({
              type: "success",
              message: res.msg
            });
            getdatsa()
          }
        }).finally(() => {
          loading.value = false
        });
      }
    });
  } else {
    addDialog({
      title: item.commandName,
      width: "428px",
      draggable: true,
      fullscreenIcon: true,
      props: {
        options: item.value3,
        modelValue: null,
        isLoading: true
      },
      hideFooter: false,
      closeOnClickModal: false,
      footerButtons: [
        {
          label: "取消",
          text: false,
          bg: true,
          btnClick: ({ dialog: { options, index } }) => {
            const done = () =>
              closeDialog(options, index, { command: "cancel" });
            if (options?.beforeCancel && isFunction(options?.beforeCancel)) {
              options.beforeCancel(done, { options, index });
            } else {
              done();
            }
          }
        },
        {
          label: "确定",
          type: "primary",
          text: false,
          bg: true,
          loading: loading,
          btnClick: ({ dialog: { options, index } }) => {
            const done = () =>
              closeDialog(options, index, { command: "sure" });
            if (options?.beforeSure && isFunction(options?.beforeSure)) {
              options.beforeSure(done, { options, index });
            } else {
              done();
            }
          }
        }
      ],
      contentRenderer: () =>
        h(dataselect, {
          ref: formRef,
          "onUpdate:modelValue": val => {
            selectidvalue.value = val;
          }
        }),
      openAutoFocus({ options }) {
        options.props = {
          isLoading: true,
          modelValue: null,
          options: item.value3,
          activevalue: null
        };
        if (item.hasConfig == 1) {
          commandconfig({
            deviceSN: props.deviceinfo.deviceSN,
            commandAlias: item.commandAlias
          })
            .then(res => {
              options.props.activevalue = res.result;
              options.props.isLoading = false;
            })
            .catch(() => {
              options.props.isLoading = false;
              ElMessage({
                type: "error",
                message: "读取配置失败"
              });
            });
        } else {
          options.props.isLoading = false;
        }

      },
      beforeSure: (done) => {
        if (selectidvalue.value == null) {
          ElMessage({
            type: "warning",
            message: "请选择"
          });
          return;
        }
        loading.value = true
        getControlops({
          deviceId: props.deviceId,
          commandId: item.commandId,
          commandArg: selectidvalue.value
        }).then((res: any) => {
          if (res.code == 200) {
            done();
            ElMessage({
              type: "success",
              message: res.msg
            });
            getdatsa()
          }
        }).finally(() => {
          loading.value = false
        });
      }
    });
  }
};
</script>
